package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    /**
     * 定义切点：拦截com.itheima.controller包下所有类的所有方法
     * 或者可以更精确地只拦截增删改方法
     */
    @Pointcut("@annotation(com.itheima.annotation.Log)")
    public void operateLogPointcut() {
    }

    /**
     * 环绕通知记录操作日志
     */
    @Around("operateLogPointcut()")
    public Object recordOperateLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取当前操作人ID（根据实际业务获取，这里示例从SecurityContext或ThreadLocal中获取）
        Integer operateEmpId = getCurrentOperateEmpId();

        // 记录开始时间
        long startTime = System.currentTimeMillis();

        // 获取目标类名和方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();

        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = this.parseParams(args);

        Object result = null;
        try {
            // 执行目标方法
            result = joinPoint.proceed();
            return result;
        } finally {
            // 记录结束时间
            long endTime = System.currentTimeMillis();
            long costTime = endTime - startTime;

            // 构建操作日志对象
            OperateLog operateLog = new OperateLog();
            operateLog.setOperateEmpId(operateEmpId);
            operateLog.setOperateTime(LocalDateTime.now());
            operateLog.setClassName(className);
            operateLog.setMethodName(methodName);
            operateLog.setMethodParams(methodParams);
            operateLog.setReturnValue(result != null ? result.toString() : "");
            operateLog.setCostTime(costTime);

            // 保存操作日志（异步保存避免影响主业务流程）
            saveOperateLog(operateLog);
            log.info("操作日志：{}", operateLog);
        }
    }

    /**
     * 解析方法参数
     */
    private String parseParams(Object[] params) {
        if (params == null || params.length == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (Object param : params) {
            sb.append(param).append(";");
        }
        return sb.toString();
    }

    /**
     * 保存操作日志（异步处理）
     */
    @Async
    public void saveOperateLog(OperateLog operateLog) {
        try {
            operateLogMapper.insert(operateLog);
        } catch (Exception e) {
            log.error("保存操作日志失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 获取当前操作人ID
     */
    private Integer getCurrentOperateEmpId() {

        return CurrentHolder.getCurrentId();

    }
}


